package datasource

import (
	"github.com/gohouse/gorose/v2"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	log "github.com/micro/go-micro/v2/logger"
	"web-service/admin-api/config"
)

//未使用gorose自带的cluster读写分离方案,以便有更好的读写自由度
type DBManager struct {
	master *gorose.Engin
	slave  *gorose.Engin
}

var dbManager DBManager

func InitDatabase() {
	config := config.GetConfig()
	var masterConfig = &gorose.Config{Driver: "mysql", Dsn: config.DBMaster.DataSourceName}
	dbManager.master = NewMysqlEngine(masterConfig)

	if len(config.DBSlave.DataSourceName) > 0 {
		var slaveConfig = &gorose.Config{Driver: "mysql", Dsn: config.DBSlave.DataSourceName}
		dbManager.slave = NewMysqlEngine(slaveConfig)
	}
}

func GetDB() *gorose.Engin {
	return dbManager.master
}

func GetDBSlave() *gorose.Engin {
	return dbManager.slave
}

func NewOrm() gorose.IOrm {
	return GetDB().NewOrm()
}

func NewSlaveOrm() gorose.IOrm {
	return GetDBSlave().NewOrm()
}

/**
 * 实例化数据库引擎方法：mysql的数据引擎
 */
func NewMysqlEngine(config *gorose.Config) *gorose.Engin {
	//var err error
	if engin, err := gorose.Open(config); err != nil {
		log.Fatal("连接数据库失败:", config.Driver, err)
		panic(err)
	} else {
		log.Info("连接数据库成功:", config)
		return engin
	}
}
